//创建用户相关小仓库tac
import { defineStore } from 'pinia'
import { reLogin, reUserInfo, reLogout } from '@/api/user/index'
import type {
  loginForm,
  loginResponse,
  userInfoResponse,
} from '@/api/user/type'
import type { UserState } from './types/type'
import { constantRouter } from '@/router/routers'
let useUserStore = defineStore('User', {
  //小仓库存储数据的地方
  state: (): UserState => {
    return {
      token: localStorage.getItem('token'),
      menuRoutes: constantRouter, //仓库存储路由菜单数据
      userInfos: {}, //存储登录后获取用户信息
    }
  },
  //异步||逻辑的地方
  actions: {
    //用户登录的方法
    async userLogin(data: loginForm) {
      let res: loginResponse = await reLogin(data)
      if (res.code == 200) {
        this.token = res.data
        localStorage.setItem('token', res.data as string)
        return true
      } else {
        return Promise.reject(new Error(res.data))
      }
      // reLogin
    },
    //获取用户信息的方法
    async getUserInfo() {
      let result: userInfoResponse = await reUserInfo()
      if (result.code == 200) {
        this.userInfos.name = result.data.name
        this.userInfos.avatar = result.data.avatar
        return 'ok'
      } else {
        return Promise.reject('获取用户信息失败')
      }
    },
    //退出登录方法
    async userLogOut() {
      let result2 = await reLogout()
      console.log(result2, 'result')
      ;(this.token = null),
        (this.userInfos = null),
        localStorage.removeItem('token')
    },
  },
  getters: {},
})

export default useUserStore
